import random
#所有的数
numArr = []
#行数
rowNum=5
#分数
score = 0
#当前的方向
currentDirect=""
'''
输出
'''
def output():
    for i in range(0,len(numArr)):
        print('{:^4}'.format(numArr[i]),end="")
        if((i+1)%rowNum == 0):
            print("")
    print("************************\n当前得分: "+ str(score) +"分\n按WASD进行移动,R重新开始")

#判断是否有可移动的数
def isCanMove():
    if 0 in numArr:
        return True
    else:
        #数组不包含0了，验证是否可消除
        for i in range(0,len(numArr)):
            num = numArr[i]
            if (((i-4>=0) and (num != numArr[i-4])) or (i-4<0)):
                #上不可移动
                pass
            else:
                return True
            if (((i+4<len(numArr)) and (num != numArr[i + 4])) or (i+4>=len(numArr))):
                #下不可移动
                pass
            else:
                return True
            if (((i-1>=0) and (num != numArr[i-1])) or (i-1<0)):
                #左不可移动
                pass
            else:
                return True
            if (((i+1<len(numArr)) and (num != numArr[i+1])) or (i+1>=len(numArr))):
                #右不可移动
                pass
            else:
                return True
        return  False
#更新数组添加随机数
def updateArr():
    # numArr中为0的项的index
    indexArr=[]
    for i in range(0,len(numArr)):
        if (numArr[i] == 0):
            indexArr.append(i)
    #选择随机数，指定一个变为2
    randomIndex = random.randint(0,len(indexArr) - 1)
    index = indexArr[randomIndex]
    numArr[index] = 2

def moveRightOrLeft():
    global numArr
    oldScore = score
    newArr = numArr[:]
    #获取每一行的所有数，进行依次对比相加
    for i in range(0, len(numArr)):
        if((i%rowNum) == 0):
            #筛选的是每行的数集合
            rowArr = []
            for j in range(i,i+rowNum):
                if (numArr[j] != 0):
                    rowArr.append(numArr[j])
            #把每行的数处理后移至末尾
            calculateRow(rowArr,len(rowArr) - 1)
            #给数组赋值
            for m in range(i, i + rowNum):
                newArr[m] = rowArr[m-i]
    #判断数组和分数有没有变化，没有则只输出不随机增加
    if(newArr != numArr or oldScore != score):
        numArr = newArr
        updateArr()
    output()
    if(isCanMove()):
        doAction()
    else:
        print("game over\n按任意键重新开始")
        input()
        start()

def moveDownOrTop():
    global numArr
    oldScore = score
    newArr = numArr[:]
    #获取每一列的数
    for i in range(0,len(numArr)):
        if(i<rowNum):
            #筛选每一列
            columArr = []
            for j in range(0,rowNum):
                index = i + j * rowNum
                if(numArr[index] != 0):
                    columArr.append(numArr[index])
            calculateRow(columArr,len(columArr) - 1)
            for m in range(0,rowNum):
                newArr[i + m*rowNum] = columArr[m]
    # 判断数组和分数有没有变化，没有则只输出不随机增加
    if(newArr != numArr or oldScore != score):
        numArr = newArr
        updateArr()
    output()
    if(isCanMove()):
        doAction()
    else:
        print("game over\n按任意键重新开始")
        input()
        start()
'''
将数组元素进行计算
'''
def calculateRow(rowArr,endIndex):
    global score
    orginIndex = endIndex
    for i in range(endIndex,0,-1):
        if (rowArr[i] == rowArr[i-1]):
            score = score + 2 * rowArr[i]
            rowArr[i-1] = rowArr[i] * 2
            rowArr.pop(i)
            endIndex = i - 2
            break
    if(endIndex >= 1 and orginIndex != endIndex):
        calculateRow(rowArr,endIndex)
    else:

        for k in range(0, rowNum):
            if (len(rowArr) < rowNum):
                if(currentDirect == "w" or currentDirect == "a"):
                    rowArr.append(0)
                else:
                    rowArr.insert(0, 0)
            else:
                break
        return rowArr

def start():
    global score
    global rowNum
    score = 0
    numArr.clear()

    print("请输入游戏的阶数: ",end="")
    str = input()
    if str.isdigit():
        if int(str) >10:
            print("请输入小一点")
            start()
            return
        elif int(str)<4:
            print("请输入大一点")
            start()
            return
        else:
            rowNum = int(str)
    else:
        print("请输入数字")
        start()
        return

    for i in range(0, rowNum ** 2):
        numArr.append(0)
    updateArr()
    updateArr()
    output()
    doAction()

def doAction():
    action = input()
    global currentDirect
    currentDirect = action
    if (action == "d" or action == "a"):
        moveRightOrLeft()
    elif (action == "s" or action == "w"):
        moveDownOrTop()
    elif (action == "r"):
        start()
    else:
        print("输入有误，重新输入")
        doAction()

#入口
start()